import { PlaceUseLog } from './../../models/plactType';
import { Subscription } from 'rxjs';
import { Component, OnInit, OnDestroy } from '@angular/core';
import * as Enumerable from 'linq';
import { PlaceUseAxisService } from './place-use-axis.service';
import * as dayjs from 'dayjs';

@Component({
  selector: 'zepride-place-use-axis',
  templateUrl: './place-use-axis.component.html',
  styleUrls: ['./place-use-axis.component.less']
})
export class PlaceUseAxisComponent implements OnInit, OnDestroy {
  fragmentList: UseAxisFragment[] = [];
  begin: number;
  end: number;

  subId: Subscription;

  constructor(
    private svr: PlaceUseAxisService
  ) { }

  ngOnDestroy(): void {
    if (this.subId) {
      this.subId.unsubscribe();
    }
  }

  ngOnInit() {
    this.svr.setDataValue$.subscribe(data => {
      this.fragmentList = data.fragmentList;
      this.begin = data.begin;
      this.end = data.end;

      this.fragmentList = Enumerable.from(this.fragmentList).orderBy(x => x.fromTime).toArray();

      this.fragmentList.forEach(item => {
        const timeLength = this.end - this.begin;
        const fragmentPonit = item.toTime - item.fromTime;

        item.proportion = fragmentPonit / timeLength * 100;
      });

    });
  }

  selectTimeSpace(item: UseAxisFragment) {
    if (item.status == 'free') {
      this.svr.selectedFreeFragment$.next(item);
    }
  }

}

export class UseAxisFragment {
  proportion: number;
  data: PlaceUseLog;
  constructor(
    public fromTime: number,
    public toTime: number,
    public status: 'using' | 'free'
  ) {
    // console.log('UseAxisFragment', dayjs(fromTime).format('YYYY-MM-DD HH:mm'), dayjs(toTime).format('YYYY-MM-DD HH:mm'), status);

  }
}
